package com.example.javapoint.threads.communication;

import java.math.BigDecimal;

class Consumer {
    private BigDecimal amount = new BigDecimal(1000);

    // 我想取的钱
    private BigDecimal drawMoney;

    /**
     * 取钱：如果取的钱比余额还多，就让线程等待
     *
     * @param amount 金额
     */
    public synchronized void withDraw(BigDecimal amount) {
        drawMoney = amount;
        if (this.amount.compareTo(amount) < 0) {
            System.out.println("大爷，钱不够了，去存点吧！");
            try {
                wait();
            } catch (InterruptedException e) {
                System.out.println("取钱的时候线程死了");
            }
        }
        System.out.println("取款完成，一共取了" + amount);
    }

    /**
     * 存钱
     *
     * @param amount 金额
     */
    public synchronized void deposit(BigDecimal amount) {
        System.out.println("开始存款。。。。。。");
        this.amount = this.amount.add(amount);
        System.out.println("还剩下余额 " +  this.amount.subtract(drawMoney));
        notify();
    }
}
public class TestWait {
    public static void main(String[] args) {
        Consumer c = new Consumer();
        // 取1500
        new Thread(() -> {
            c.withDraw(new BigDecimal(1500));
        }).start();

        // 存300 不够
        new Thread(() -> {
            c.deposit(new BigDecimal(300));
        }).start();

        // 存100 不够取
        new Thread(()->{
            c.deposit(new BigDecimal(100));
        }).start();

        // 存200 够取了
        new Thread(()->{
            c.deposit(new BigDecimal(200));
        }).start();
    }
}
